package cn.laixueit.filter;

import cn.laixueit.properties.FilterProperties;
import cn.laixueit.properties.JwtProperties;
import cn.laixueit.utils.CookieUtils;
import cn.laixueit.utils.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class ZuuFilter extends ZuulFilter {

    @Autowired
    private JwtProperties properties;
    @Autowired
    private FilterProperties filterProperties;

    @Override
//    什么时候执行
    public String filterType() {
        return "pre";
    }

    @Override
//    执行等级
    public int filterOrder() {
        return 10;
    }

    @Override
//    是否执行run方法
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();
        List<String> paths = filterProperties.getAllowPaths();
        for (String path : paths) {
            if (uri.startsWith(path)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        String token = CookieUtils.getCookieValue(request, properties.getCookieName());

        try {
            // 正常就执行
            JwtUtils.getInfoFromToken(token,properties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常就校验失败
            context.setSendZuulResponse(false); // 不转发
            context.setResponseStatusCode(HttpStatus.SERVICE_UNAVAILABLE.value());
        }

        return null;
    }
}
